package com.mgq.netty.chat.client;

import com.mgq.netty.chat.message.RpcResponseMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@ChannelHandler.Sharable
public class RpcResponseHandler extends SimpleChannelInboundHandler<RpcResponseMessage> {
    /**
     * promise中保存的是返回值
     */
    public static final Map<Integer, Promise<Object>> PROMISE_MAP = new ConcurrentHashMap();


    @Override

    protected void channelRead0(ChannelHandlerContext ctx, RpcResponseMessage msg) throws Exception {
        log.debug("msg{}", msg);
        //注意,使用remove()方法,而不是get(),每次调用完成后,promise对象已经不再使用了.
        Promise<Object> promise = PROMISE_MAP.remove(msg.getSequenceId());
        if (promise != null) {
            //失败
            if (msg.getExceptionValue() != null) {
                promise.setFailure(msg.getExceptionValue());
            } else {
                promise.setSuccess(msg.getReturnValue());
            }
        }

    }
}
